package com.atguigu.spzx.pay.service.impl;

import java.math.BigDecimal;
import java.util.*;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.alipay.api.response.AlipayTradeWapPayResponse;
import com.atguigu.order.feign.OrderFeignClient;
import com.atguigu.product.feign.ProductFeignClient;
import com.atguigu.spzx.model.pojo.order.OrderInfo;
import com.atguigu.spzx.model.pojo.order.OrderItem;
import com.atguigu.spzx.model.vo.common.Result;
import com.atguigu.spzx.pay.mapper.PaymentInfoMapper;
import com.atguigu.spzx.pay.utils.AlipayProperties;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.spzx.model.pojo.h5.PaymentInfo;
import com.atguigu.spzx.pay.service.PaymentInfoService;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author 17605
 * @description 针对表【payment_info(付款信息表)】的数据库操作Service实现
 * @createDate 2025-01-29 14:44:55
 */
@Service
@Transactional
@Slf4j
public class PaymentInfoServiceImpl extends ServiceImpl<PaymentInfoMapper, PaymentInfo>
        implements PaymentInfoService {

    @Autowired
    private AlipayProperties alipayProperties;

    @Autowired
    private AlipayClient alipayClient;

    @Autowired
    private OrderFeignClient orderFeignClient;

    @Autowired
    private PaymentInfoMapper paymentInfoMapper;

    @Autowired
    private ProductFeignClient productFeignClient;

    /**
     * @param orderNo
     * @return
     * @doc: 支付宝提交订单
     * @author 17605
     * @date 2025/01/29
     */
    @Override
    public String submitAlipay(String orderNo) throws AlipayApiException {
        // 查询支付信息数据，如果已经已经存在了就不用进行保存(一个订单支付失败以后可以继续支付)
        PaymentInfo paymentInfo = paymentInfoMapper.getByOrderNo(orderNo);
        if(null == paymentInfo) {
            OrderInfo orderInfo = orderFeignClient.findByOrderNo(orderNo).getData();
            paymentInfo = new PaymentInfo();
            paymentInfo.setUserId(orderInfo.getUserId());
            paymentInfo.setPayType(orderInfo.getPayType());
            StringBuilder content = new StringBuilder();
            for(OrderItem item : orderInfo.getOrderItemList()) {
                content.append(item.getSkuName()).append(" ");
            }
            paymentInfo.setContent(content.toString());
            paymentInfo.setAmount(orderInfo.getTotalAmount());
            paymentInfo.setOrderNo(orderNo);
            paymentInfo.setPaymentStatus(String.valueOf(0));
            paymentInfoMapper.insert(paymentInfo);
        }

        //创建API对应的request
        AlipayTradeWapPayRequest alipayRequest = new AlipayTradeWapPayRequest();
        // 同步回调
        alipayRequest.setReturnUrl(alipayProperties.getReturnPaymentUrl());
        // 异步回调
        alipayRequest.setNotifyUrl(alipayProperties.getNotifyPaymentUrl());

        // 准备请求参数 ，声明一个map 集合
        HashMap<String, Object> map = new HashMap<>();
        map.put("out_trade_no", paymentInfo.getOrderNo());
        map.put("product_code", "QUICK_WAP_WAY");
        map.put("total_amount", paymentInfo.getAmount());
        map.put("subject", paymentInfo.getContent());
        alipayRequest.setBizContent(JSON.toJSONString(map));

        // 发送请求
        AlipayTradeWapPayResponse response = alipayClient.pageExecute(alipayRequest);
        if (response.isSuccess()) {
            log.info("调用成功");
            return response.getBody();
        } else {
            log.info("调用失败");
            throw new RuntimeException("支付宝回调失败");
        }
    }

    @Override
    public void updatePayment(Map<String, String> map, HttpServletRequest request) {
        // 更新订单状态
        // 查询PaymentInfo
        PaymentInfo paymentInfo = paymentInfoMapper.getByOrderNo(map.get("out_trade_no"));
        // 已支付
        if (Objects.equals(paymentInfo.getPaymentStatus(), String.valueOf(1))) {
            return;
        }
        //更新支付信息
        paymentInfo.setPayType(2);
        paymentInfo.setPaymentStatus(String.valueOf(1));
        paymentInfo.setOutTradeNo(map.get("trade_no"));
        paymentInfo.setCallbackTime(new Date());
        paymentInfo.setCallbackContent(JSON.toJSONString(map));
        paymentInfoMapper.updateById(paymentInfo);

        // 修改库存
        // 1、获取orderItem
        OrderInfo orderInfo = orderFeignClient.findByOrderNo(paymentInfo.getOrderNo()).getData();
        List<OrderItem> orderItemList = orderInfo.getOrderItemList();
        // 2、修改库存和销量
        for (OrderItem orderItem : orderItemList) {
            productFeignClient.updateStormAndSale(orderItem.getSkuId(),orderItem.getSkuNum());
        }
        //TODO 2025/2/1 在购物车服务中，删除购物车
    }
}




